package com.ruoyi.washer.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.washer.common.WxWechatTools;
import com.ruoyi.washer.domain.XwAgent;
import com.ruoyi.washer.domain.XwEnduser;
import com.ruoyi.washer.domain.XwProduct;
import com.ruoyi.washer.service.impl.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/wechat")
public class WeChatController01 {

    private static final Logger logger = LoggerFactory.getLogger(WeChatController01.class);

    @Autowired
    private WxWechatTools wxWechatTools;

    @Autowired
    private XwAgentServiceImpl xwAgentServiceImpl;

    @Autowired
    private XwDeviceServiceImpl xwDeviceServiceImpl;

    @Autowired
    private XwWashballServiceImpl xwWashballServiceImpl;

    @Autowired
    private XwEnduserServiceImpl xwEnduserServiceImpl;

    @Autowired
    private XwEnduserTeamServiceImpl xwEnduserTeamServiceImpl;

    @Autowired
    private XwProductServiceImpl xwProductServiceImpl;

    @Autowired
    private XwPurchaseOrderServiceImpl xwPurchaseOrderServiceImpl;

    @Autowired
    private XwCompanyServiceImpl xwCompanyServiceImpl;
    /*
    获取当前用户的openid
     */
    @GetMapping("/open/get/openid/by/code")
    public AjaxResult getOpenIdByCode(@RequestParam("code") String code){
        AjaxResult ajax = AjaxResult.success();
        try{
            String openId=wxWechatTools.getOpenid(code);
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("openId",openId);
            ajax.put("data",jsonObject);
        }catch (Exception e){
            ajax=new AjaxResult(HttpStatus.BAD_REQUEST, "获取openid出现异常");
        }
        return ajax;
    }
    /*
    获取代理人信息
     */
    @GetMapping("/open/get/agent/message")
    public AjaxResult getAgentMessage(@RequestParam("openId") String openId){
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data",xwAgentServiceImpl.getAgentMessage(openId));
        return ajax;
    }
    /*
    代理人注册
     */
    @PostMapping("/open/agent/bing/msg")
    public AjaxResult setAgentBingMsg(@RequestBody XwAgent xwAgent){
        AjaxResult ajax = AjaxResult.success();
        int flag=xwAgentServiceImpl.setAgentBingMsg(xwAgent);
        if(flag==1){
            ajax=new AjaxResult(HttpStatus.BAD_REQUEST, "当前登录用户已经申请过");
        }else if(flag==2){
            ajax=new AjaxResult(HttpStatus.SUCCESS, "申请成功，请等待审核");
        }
        return ajax;
    }
    /*
    获取当前代理人的设备信息
     */
    @GetMapping("/open/get/agent/device/list")
    public AjaxResult getAgentDeviceList(@RequestParam("openId") String openId){
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data",xwAgentServiceImpl.getAgentDeviceList(openId));
        return ajax;
    }
    /*
获取当前终端经营用户的设备信息
 */
    @GetMapping("/open/get/enduser/device/list")
    public AjaxResult getEnduserDeviceList(@RequestParam("openId") String openId){
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data",xwEnduserServiceImpl.getEnduserDeviceList(openId));
        return ajax;
    }
    /*
    设备入库处理，type=1代理入库 2是终端入库
     */
    @GetMapping("/open/save/device")
    public AjaxResult saveDevice(@RequestParam("openId") String openId,
                                 @RequestParam("deviceSn") String deviceSn,
                                 @RequestParam("type") String type){
        AjaxResult ajax = AjaxResult.success();
        int flag=xwDeviceServiceImpl.saveDevice(openId,deviceSn,type);
        if(flag==0){
            ajax=new AjaxResult(HttpStatus.BAD_REQUEST, deviceSn+"\n系统找不到对应的设备");
        }else if(flag==1){
            ajax=new AjaxResult(HttpStatus.BAD_REQUEST, deviceSn+"\n已经入库了此设备，不用重复入库");
        }else if(flag==2){
            ajax=new AjaxResult(HttpStatus.BAD_REQUEST, deviceSn+"\n其他用户已经入库了此设备");
        }else if(flag==3){
            ajax=new AjaxResult(HttpStatus.SUCCESS, deviceSn+"\n设备入库成功");
        }
        return ajax;
    }
        /*
    获取当前代理人的设备信息
     */
    @GetMapping("/open/get/agent/washball/list")
    public AjaxResult getAgentWashballList(@RequestParam("openId") String openId){
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data",xwWashballServiceImpl.getAgentWashballList(openId));
        return ajax;
    }

    /*
    获取当前终端的个人信息
     */
    @GetMapping("/open/get/enduser/message")
    public AjaxResult getEnduserMessage(@RequestParam("openId") String openId){
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data",xwEnduserServiceImpl.getEnduserMessage(openId));
        return ajax;
    }
    /*
    终端经营用户注册登记
     */
    @PostMapping("/open/save/enduser/message")
    public AjaxResult saveEnduserMessage(@RequestBody XwEnduser xwEnduser){
        AjaxResult ajax = null;
        int flag=xwEnduserServiceImpl.saveEnduserMessage(xwEnduser);
        if(flag==1){
            ajax=new AjaxResult(HttpStatus.BAD_REQUEST, "当前用户已经注册过");
        }else {
            ajax=new AjaxResult(HttpStatus.SUCCESS, "注册成功");
        }
        return ajax;
    }
    /*
    获取当前用户的补货员团队
     */
    @GetMapping("/open/get/enduser/replenishman")
    public AjaxResult getEnduserReplenishmanList(@RequestParam("openId") String openId){
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data",xwEnduserTeamServiceImpl.getEnduserReplenishmanList(openId));
        return ajax;
    }
    /*
    删除补货员
    * */
    @GetMapping("/open/delete/enduser/replenishman")
    public AjaxResult deleteEnduserReplenishmanByTeamId(@RequestParam("teamId") String teamId){
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data",xwEnduserTeamServiceImpl.deleteEnduserReplenishmanByTeamId(teamId));
        return ajax;
    }
    /*
    创建终端团队的邀请码
     */
    @GetMapping("/open/create/enduser/invitation/code")
    public AjaxResult createEnduserInvitationCode(@RequestParam("openId") String openId){
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data",xwEnduserTeamServiceImpl.createEnduserInvitationCode(openId));
        return ajax;
    }
    /*
    获取自己作为补货员的团队
     */
    @GetMapping("/open/get/join/replenishman")
    public AjaxResult getJoinReplenishmanList(@RequestParam("openId") String openId){
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data",xwEnduserTeamServiceImpl.getJoinReplenishmanList(openId));
        return ajax;
    }
    /*
    根据邀请码绑定补货员
     */
    @GetMapping("/open/bing/replenishman/by/invitationcode")
    public AjaxResult bingReplenishmanByInvitationcode(@RequestParam("openId") String openId,
                                                       @RequestParam("invitationCode") String invitationCode){
        AjaxResult ajax = AjaxResult.success();
        int flag=xwEnduserTeamServiceImpl.bingReplenishmanByInvitationcode(openId,invitationCode);
        if(flag==1){
            ajax=new AjaxResult(HttpStatus.BAD_REQUEST, "邀请码不合法或者已经过期或者已经绑定过");
        }else{
            ajax=new AjaxResult(HttpStatus.SUCCESS, "绑定成功");
        }
        return ajax;
    }
    /*
        根据设备的SN获取设备的信息
     */
    @GetMapping("/open/get/device/by/devicesn")
    public AjaxResult getDeviceByDeviceSn(@RequestParam("deviceSn") String deviceSn){
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data",xwDeviceServiceImpl.getDeviceByDeviceSn(deviceSn));
        return ajax;
    }
    /*
    获取所有产品信息
     */
    @GetMapping("/open/get/all/product/list")
    public AjaxResult getAllProductList(){
        AjaxResult ajax = AjaxResult.success();
        XwProduct xwProduct=new XwProduct();
        ajax.put("data",xwProductServiceImpl.selectXwProductList(xwProduct));
        return ajax;
    }
    /*
    保存设备格子的产品设置
     */
    @GetMapping("/open/save/devcie/grid/state")
    public AjaxResult saveDevcieGridState(@RequestParam("index") String index,
                                            @RequestParam("deviceSn") String deviceSn,
                                            @RequestParam("stateType") String stateType){
        System.out.println("stateType=========="+stateType);
        AjaxResult ajax = AjaxResult.success();
        int flag=xwDeviceServiceImpl.saveDevcieGridProduct(index,deviceSn,stateType);
        if(flag!=1){
            ajax=new AjaxResult(HttpStatus.BAD_REQUEST, "保存失败，请重试");
        }
        return ajax;
    }
    /*
   保存设备的补货状态
     */
    @GetMapping("/open/save/devcie/repair/flag")
    public AjaxResult saveDevcieRepairFlag(
                                            @RequestParam("deviceSn") String deviceSn,
                                            @RequestParam("repairFlag") String repairFlag){
        AjaxResult ajax = AjaxResult.success();
        int flag=xwDeviceServiceImpl.saveDevcieRepairFlag(deviceSn,repairFlag);
        if(flag!=1){
            ajax=new AjaxResult(HttpStatus.BAD_REQUEST, "保存失败，请重试");
        }
        return ajax;
    }
    /**
     *解绑设备，type=1 代理商解绑，type=2 终端解绑
     */
    @GetMapping("/open/unbing/devcie")
    public AjaxResult unBingDeviceState(
            @RequestParam("deviceSn") String deviceSn,
            @RequestParam("type") String type,
            @RequestParam("openId") String openId){
        AjaxResult ajax = null;
        int flag=xwDeviceServiceImpl.unBingDeviceState(deviceSn,type,openId);
        if(flag!=1){
            ajax=new AjaxResult(HttpStatus.BAD_REQUEST, "解绑失败，请重试");
        }else{
            ajax=new AjaxResult(HttpStatus.SUCCESS, "解绑成功");
        }
        return ajax;
    }
    /*
    获取消费者的订单列表
     */
    @GetMapping("/open/get/client/orders")
    public AjaxResult getClientOrders(
            @RequestParam("openId") String openId){
        AjaxResult ajax = new AjaxResult(HttpStatus.SUCCESS, "获取成功");
        ajax.put("data",xwPurchaseOrderServiceImpl.getClientOrders(openId));
        return ajax;
    }
    /*
    保存终端的提现设置
     */
    @GetMapping("/open/save/enduser/cashout/settings")
    public AjaxResult saveEnduserCashoutSettings(
            @RequestParam("cashoutType") String cashoutType,
            @RequestParam("enduserMerchantCode") String enduserMerchantCode,
            @RequestParam("enduserMerchantName") String enduserMerchantName,
            @RequestParam("openId") String openId){
        AjaxResult ajax = new AjaxResult(HttpStatus.SUCCESS, "保存成功");
        xwEnduserServiceImpl.saveEnduserCashoutSettings(cashoutType,enduserMerchantCode,
                enduserMerchantName,openId);
        return ajax;
    }
    /*
保存代理人的提现设置
 */
    @GetMapping("/open/save/agent/cashout/settings")
    public AjaxResult saveAgentCashoutSettings(
            @RequestParam("cashoutType") String cashoutType,
            @RequestParam("agentMerchantCode") String agentMerchantCode,
            @RequestParam("agentMerchantName") String agentMerchantName,
            @RequestParam("openId") String openId){
        AjaxResult ajax = new AjaxResult(HttpStatus.SUCCESS, "保存成功");
        xwAgentServiceImpl.saveAgentCashoutSettings(cashoutType,agentMerchantCode,
                agentMerchantName,openId);
        return ajax;
    }
    /*
    归还洗衣球处理
     */
    @GetMapping("/open/deal/give/back/ball")
    public AjaxResult dealGiveBackBall(
            @RequestParam("washballSn") String washballSn,
            @RequestParam("deviceSn") String deviceSn,
            @RequestParam("openId") String openId){
        AjaxResult ajax = null;
        try{
        int flag=xwPurchaseOrderServiceImpl.dealGiveBackBall(washballSn,deviceSn,openId);
        if(flag==1){
            ajax=new AjaxResult(HttpStatus.BAD_REQUEST, "没有找到需要归还的订单");
        }else if(flag==2){
            ajax=new AjaxResult(HttpStatus.BAD_REQUEST, "不是同一个终端的设备，请移步去原租借点归还");
        }else{
            ajax=new AjaxResult(HttpStatus.SUCCESS, "归还成功，请注意查收退款信息，信息有延迟");
        }
        }catch (Exception e){
            logger.error("归还扣费发生异常：",e.getMessage());
            e.printStackTrace();
            ajax=new AjaxResult(HttpStatus.BAD_REQUEST, "归还发生异常，请重试");
        }
        return ajax;
    }
    /*
    扫码进去处理异常订单
     */
    @GetMapping("/open/deal/error/rent/ball/list")
    public AjaxResult dealErrorRentBallList(
            @RequestParam("washballSnStr") String washballSnStr,
            @RequestParam("deviceSn") String deviceSn,
            @RequestParam("openId") String openId){
        AjaxResult ajax=new AjaxResult(HttpStatus.SUCCESS, "处理成功");
        try{
            logger.error("异常格子清单："+washballSnStr);
            logger.error("异常格子球编号："+deviceSn);
            logger.error("异常格子openId："+openId);
            String washballSnList[]=washballSnStr.split(",");
            for(int i=0;i<washballSnList.length;i++){
                String washballSn=washballSnList[i];
                if(washballSn==null||washballSn.equals("")) {continue;}
                logger.error("异常格子的SN："+washballSn);
                int flag=xwPurchaseOrderServiceImpl.dealGiveBackBall(washballSn,deviceSn,openId);
                logger.error("flag："+flag);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("自动归还异常信息："+e.getMessage());
            ajax=new AjaxResult(HttpStatus.BAD_REQUEST, "归还发生异常，请重试");
        }
        return ajax;
    }

    /*
获取终端的订单列表
 */
    @GetMapping("/open/get/enduser/orders")
    public AjaxResult getEnduserOrders(
            @RequestParam("openId") String openId){
        AjaxResult ajax = new AjaxResult(HttpStatus.SUCCESS, "获取成功");
        ajax.put("data",xwPurchaseOrderServiceImpl.getEnduserOrders(openId));
        return ajax;
    }
    /*
获取代理的订单列表
*/
    @GetMapping("/open/get/agent/orders")
    public AjaxResult getAgentOrders(
            @RequestParam("openId") String openId){
        AjaxResult ajax = new AjaxResult(HttpStatus.SUCCESS, "获取成功");
        ajax.put("data",xwPurchaseOrderServiceImpl.getAgentOrders(openId));
        return ajax;
    }

    /*
    获取终端的补货设备清单
     */
    @GetMapping("/open/get/repair/list")
    public AjaxResult getRepairList(
            @RequestParam("openId") String openId){
        AjaxResult ajax = new AjaxResult(HttpStatus.SUCCESS, "获取成功");
        ajax.put("data",xwDeviceServiceImpl.getRepairList(openId));
        return ajax;
    }
    /*
修改设备部署地址
 */
    @GetMapping("/open/save/device/address")
    public AjaxResult saveDeviceAddress(
            @RequestParam("deviceSn") String deviceSn,
            @RequestParam("deviceAddress") String deviceAddress){
        AjaxResult ajax = new AjaxResult(HttpStatus.SUCCESS, "获取成功");
        xwDeviceServiceImpl.saveDeviceAddress(deviceSn,deviceAddress);
        return ajax;
    }
    /*
补货员扫码补货检查是否是合法设备
*/
    @GetMapping("/open/check/device/for/replenishment")
    public AjaxResult checkDeviceForReplenishment(
            @RequestParam("deviceSn") String deviceSn,
            @RequestParam("openId") String openId){
        AjaxResult ajax = new AjaxResult(HttpStatus.SUCCESS, "获取成功");
        int flag=xwDeviceServiceImpl.checkDeviceForReplenishment(deviceSn,openId);
        if(flag==0){
            ajax = new AjaxResult(HttpStatus.BAD_REQUEST, "本设备不属于你管理的范围");
        }
        return ajax;
    }
    /*
    获取公司信息
     */
    @GetMapping("/open/get/about/company")
    public AjaxResult getAboutCompany(){
        AjaxResult ajax = new AjaxResult(HttpStatus.SUCCESS, "获取成功");
        ajax.put("data",xwCompanyServiceImpl.getAboutCompany());
        return ajax;
    }
}
